package spl.utils;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Ruby
 *
 */
public class GlobalLogger{ 
	private static boolean initialized = false;
	public Logger logger;
	/**
	 * Returns the global logger of the programs
	 * @param filePath to store logger on disk.
	 */
	public GlobalLogger(String filePath){
		this.logger = Logger.getLogger("GlobalLog");
		makeSureInit(filePath);
	}
	/**
	 * Return already initialized logger.
	 */
	public GlobalLogger(){
		this.logger = Logger.getLogger("GlobalLog");
		makeSureInit(null);
	}
	
	/**
	 * Factory to the global logger.
	 * @return default global logger.
	 */
	public static Logger getLogger() {
		GlobalLogger gl = new GlobalLogger();
		return gl.logger;
	}
	
	/**
	 * Makes sure the logger is initialized properly.
	 * If we try to initialize it with any file path, the function
	 * assumes it is initialized and returns true.
	 * 
	 * @param filePath file path of the logger. 
	 */
	private boolean makeSureInit(String filePath){
		if(GlobalLogger.initialized | null == filePath)
			return true;
		try {
			this.logger.addHandler(new FileHandler(filePath));
			this.logger.setUseParentHandlers(false);
			this.logger.setLevel(Level.FINEST);
			GlobalLogger.initialized = true;
			return true;
		} catch (SecurityException e) {
			System.out.println("Warning: logging exception -> logging is disabled");
		} catch (IOException e) {
			System.out.println("Warning: logging exception -> logging is disabled");
		}
		return false;
	}
}
